#!/bin/bash

printf '\033]2;Browse and edit STK addon tracks\a'

dirs="$HOME/.local/share/supertuxkart/addons/tracks"
id=Zaphod

putimg() {
    {
        printf "{"
        printf '"%s": "%s", ' "action" "add" "identifier" "$id" "scaler" "distort" "x" "0" "y" "0" "width" "$width" "height" "$height" "path" "$1"
        printf '"%s": "%s" }\n' "synchronously_draw" "True"
    } > "$UEBERZUG_FIFO"
}
remimg() {
    {
        printf "{"
        printf '"%s": "%s", ' "action" "remove" "identifier" "$id"
        printf '"%s": "%s" }\n' "synchronously_draw" "True"
    } > "$UEBERZUG_FIFO"
}
getattr() {
    xmllint --nonet --xpath "string(//track/@$1)" - <<<"$xml"
}
cleanup() {
    tabs
    rm -f "$UEBERZUG_FIFO"
    tput cnorm
}
do_setup() {
    width=$(( (COLUMNS/3)*2 ))
    height=$(( LINES ))
    rest="$((COLUMNS - (width+1) ))"
    tabs $((width+1))
}
tab() { echo -en '\t'; }
tablines() { while read -r line; do tab; echo "$line"; done; }
f() { fold -s -w "$rest"; }

tput civis
trap cleanup EXIT
setup=1
offset=''

while getopts "no:" opt; do
  case $opt in
    n)
        setup=0
        ;;
    o)
        offset="$OPTARG"
        ;;
  esac
done

export UEBERZUG_FIFO="/tmp/stk-tracks-ueberzug-fifo"
rm -f "$UEBERZUG_FIFO"
mkfifo "$UEBERZUG_FIFO"
ueberzug layer --parser json < "$UEBERZUG_FIFO" &
exec 3>"$UEBERZUG_FIFO"

[[ "$setup" == 0 ]] && do_setup || {
    testimg="/usr/share/supertuxkart/data/gamerzilla/supertuxkart.png"
    #~ /usr/share/supertuxkart/data/skins/cartoon/background.jpg
    #~ /usr/share/supertuxkart/data/skins/common/background.jpg
    #~ /usr/share/supertuxkart/data/tracks/cornfield_crossing/screenshot.jpg
    txt="Terminal setup\n==============
    The image should be roughly 4:3 and there must be at least 20 char width to the right of it."
    OK=0
    wait=2 # seconds to wait before redraw
    while [[ "${OK,}" != y ]]; do
        clear
        (( COLUMNS<60 || LINES<10 )) && {
            remimg
            echo -e "${txt}\n\nTerminal too small. Current size: ${COLUMNS}x${LINES}. Please resize to at least 60x10, recommended: 80x24." | fold -s -w $COLUMNS
            sleep $wait
        } || {
            do_setup
            putimg "$testimg"
            echo -e "${txt}\n\nIf you're happy with the new size, press y _" | f | tablines
            read -s -n1 -t $wait OK
        }
    done
}

txt="\n  e - edit\n  n - next (default)\n  r - remove track\n  q - Quit"
for dir in "$dirs"/*; do
    [[ "${dir##*/}" == "$offset"* ]] || continue
    offset=""
    [ -r "$dir/track.xml" ] || continue
    xml="$(<"$dir/track.xml")"
    clear
    putimg "$dir/$(getattr screenshot)"
    {
    echo "Track:"
    getattr name | f
    echo -e "Directory:\n${dir##*/}"
    echo -n "Laps: "
    getattr default-number-of-laps
    } | tablines
    echo -e "$txt" | tablines
    while { tab; read -s -n1 -p "Action? _" x; }; do
        case "${x,}" in
            e)  remimg; nano --softwrap --atblanks "$dir/track.xml"; tput civis; putimg "$dir/$(getattr screenshot)"
            ;;
            n|'') break
            ;;
            r)  echo -e "\nReally delete ~${dir#$HOME} (y/N)? _" | f | tablines; read -s -n1 y
                [[ "${y,}" == y ]] && rm -r "$dir" && break
            ;;
            q)  clear && exit
            ;;
            *)  echo -e "\n\tinvalid input: $x"
            ;;
        esac
    done
    remimg
done
